<template>
  <header
    class="app__header p-2 border-b border-[var(--border)] bg-[var(--surface)] flex items-center justify-between">
    <div class="flex items-center gap-2">
      <img src="./assets/icon.png" alt="icon" class="w-6 h-6" />
      <div class="text-sm text-[var(--muted)]">
        <span v-if="!selectedDate">点击图标显示“查看日程”</span>
        <span v-else>点击图标显示“添加新日程”</span>
      </div>
    </div>
    <div class="font-semibold">日程推推 - 您的时间管理专家</div>
  </header>

  <main class="p-3 space-y-3">
    <section class="flex gap-3">
      <div class="flex-1 min-w-[280px]">
        <div class="mb-2 flex items-center justify-between">
          <div class="text-base font-medium">日历</div>
          <div class="flex items-center gap-2">
            <button class="btn" @click="prevMonth">上月</button>
            <div class="text-sm">
              {{ currentYear }}年{{ currentMonthIndex + 1 }}月
            </div>
            <button class="btn" @click="nextMonth">下月</button>
          </div>
        </div>
        <div class="calendar border rounded overflow-hidden">
          <div
            class="grid grid-cols-7 text-center text-xs bg-[var(--surface-2)] py-1">
            <div v-for="d in weekDays" :key="d">{{ d }}</div>
          </div>
          <div class="grid grid-cols-7">
            <div
              v-for="cell in calendarCells"
              :key="cell.key"
              class="border-t border-[var(--border)] p-2 h-20 cursor-pointer hover:bg-[var(--surface-2)]"
              :class="{
                'opacity-60': !cell.inCurrentMonth,
                'bg-[var(--surface-2)]': isSelected(cell.dateStr)
              }"
              @click="onPickDate(cell.dateStr)">
              <div class="flex items-center justify-between text-xs">
                <span>{{ cell.day }}</span>
                <span
                  v-if="hasSchedules(cell.dateStr)"
                  class="inline-block w-2 h-2 rounded-full bg-[var(--accent)]"></span>
              </div>
              <div class="mt-1 text-[10px] space-y-0.5 max-h-10 overflow-auto">
                <div
                  v-for="it in topTwoTitles(cell.dateStr)"
                  :key="it.id"
                  class="truncate">
                  • {{ it.title }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="selectedDate" class="mt-2">
          <button class="btn-primary" @click="openAddForSelected">
            点击添加日程
          </button>
        </div>
      </div>

      <div class="flex-1">
        <div class="mb-2 flex items-center justify-between">
          <div class="text-base font-medium">查询</div>
          <div class="flex items-center gap-2">
            <button class="btn" @click="loadMonth">查询当月日程</button>
          </div>
        </div>
        <div class="border rounded p-2">
          <div class="text-sm mb-2">
            {{ currentYear }}年{{ currentMonthIndex + 1 }}月 日程
          </div>
          <div
            v-if="monthSchedules.length === 0"
            class="text-xs text-[var(--muted)]">
            本月暂无日程
          </div>
          <div v-else class="space-y-2">
            <div
              v-for="it in monthSchedulesSorted"
              :key="it.id"
              class="flex items-center justify-between px-2 py-1 rounded hover:bg-[var(--surface-2)]">
              <div class="text-sm">
                <span class="mr-2">日期：{{ it.date }}</span>
                <span class="mr-2">时间：{{ it.time }}</span>
                <span class="mr-2">标题：{{ it.title }}</span>
                <span class="text-[10px] text-[var(--muted)]">{{
                  repeatLabel(it.repeat)
                }}</span>
              </div>
              <div class="flex items-center gap-2">
                <button class="btn" @click="onEdit(it)">编辑</button>
                <button class="btn-danger" @click="onDelete(it)">删除</button>
              </div>
            </div>
          </div>
        </div>

        <div class="mt-3 flex items-center gap-2 text-xs text-[var(--muted)]">
          <button class="link" @click="onHelp">需要帮助？点击这里</button>
          <span>·</span>
          <button class="link" @click="onFeedback">
            您的反馈对我们很重要，点击这里提交
          </button>
        </div>
      </div>
    </section>

    <!-- 添加/编辑 弹框 -->
    <div
      v-if="dialogVisible"
      class="fixed inset-0 bg-black/30 flex items-center justify-center">
      <div
        class="w-[360px] bg-[var(--surface)] border border-[var(--border)] rounded shadow-lg">
        <div class="px-3 py-2 border-b border-[var(--border)] font-medium">
          {{ isEditing ? "编辑日程" : "添加日程 - 请输入详情" }}
        </div>
        <div class="p-3 space-y-2">
          <div class="space-y-1">
            <div class="text-xs">标题：请输入日程标题</div>
            <input
              class="input"
              v-model="form.title"
              placeholder="请输入日程标题" />
          </div>
          <div class="space-y-1">
            <div class="text-xs">时间：选择推送时间</div>
            <input class="input" type="time" v-model="form.time" />
          </div>
          <div class="space-y-1">
            <div class="text-xs">日期：选择日期</div>
            <input class="input" type="date" v-model="form.date" />
          </div>
          <div class="space-y-1">
            <div class="text-xs">重复选项：是否重复</div>
            <select class="input" v-model="form.repeat">
              <option value="none">不重复</option>
              <option value="daily">每日</option>
              <option value="weekly">每周</option>
              <option value="monthly">每月</option>
            </select>
          </div>
          <div v-if="errorMsg" class="text-xs text-red-500">{{ errorMsg }}</div>
        </div>
        <div
          class="px-3 py-2 border-t border-[var(--border)] flex items-center justify-end gap-2">
          <button class="btn" @click="closeDialog">取消</button>
          <button class="btn-primary" @click="onSave">保存</button>
        </div>
      </div>
    </div>
  </main>
</template>

<style>
@import "./assets/styles/popup.css";
/* Basic utilities in case Tailwind not available in popup build */
.btn {
  padding: 4px 8px;
  border: 1px solid var(--border);
  border-radius: 6px;
  background: var(--surface);
}
.btn:hover {
  background: var(--surface-2);
}
.btn-primary {
  padding: 4px 10px;
  border-radius: 6px;
  background: var(--accent);
  color: white;
}
.btn-danger {
  padding: 4px 8px;
  border-radius: 6px;
  background: #ef4444;
  color: white;
}
.input {
  width: 100%;
  padding: 6px 8px;
  border: 1px solid var(--border);
  border-radius: 6px;
  background: var(--surface);
}
.link {
  color: var(--accent);
  text-decoration: underline;
}
</style>

<script setup lang="ts">
// @ts-ignore ensure editor doesn't block on transient type resolution in some environments
import { computed, onMounted, ref, watch } from "vue"

type RepeatType = "none" | "daily" | "weekly" | "monthly"
interface ScheduleItem {
  id: string
  title: string
  date: string // YYYY-MM-DD
  time: string // HH:mm
  repeat: RepeatType
  createdAt?: number
  enabled?: boolean
}

const weekDays = ["日", "一", "二", "三", "四", "五", "六"]
const today = new Date()
const currentYear = ref(today.getFullYear())
const currentMonthIndex = ref(today.getMonth()) // 0-based
const selectedDate = ref<string>("")

const dialogVisible = ref(false)
const isEditing = ref(false)
const editingId = ref<string | null>(null)
const errorMsg = ref("")
const form = ref<{
  title: string
  date: string
  time: string
  repeat: RepeatType
}>({
  title: "",
  date: "",
  time: "",
  repeat: "none"
})

const monthSchedules = ref<ScheduleItem[]>([])
const monthSchedulesSorted = computed(() =>
  [...monthSchedules.value].sort((a, b) =>
    `${a.date} ${a.time}`.localeCompare(`${b.date} ${b.time}`)
  )
)

function daysInMonth(year: number, monthIndex0: number) {
  return new Date(year, monthIndex0 + 1, 0).getDate()
}
function pad2(n: number) {
  return String(n).padStart(2, "0")
}
function toYmd(y: number, m0: number, d: number) {
  return `${y}-${pad2(m0 + 1)}-${pad2(d)}`
}

const calendarCells = computed(() => {
  const y = currentYear.value
  const m0 = currentMonthIndex.value
  const first = new Date(y, m0, 1)
  const offset = first.getDay() // 0..6 starting Sunday
  const total = daysInMonth(y, m0)
  const prevDays = daysInMonth(y, (m0 + 11) % 12)

  const cells: Array<{
    key: string
    inCurrentMonth: boolean
    day: number
    dateStr: string
  }> = []
  // leading days from previous month
  for (let i = offset - 1; i >= 0; i--) {
    const day = prevDays - i
    const date = new Date(y, m0 - 1, day)
    cells.push({
      key: `p-${day}`,
      inCurrentMonth: false,
      day,
      dateStr: toYmd(date.getFullYear(), date.getMonth(), date.getDate())
    })
  }
  // current month
  for (let d = 1; d <= total; d++) {
    cells.push({
      key: `c-${d}`,
      inCurrentMonth: true,
      day: d,
      dateStr: toYmd(y, m0, d)
    })
  }
  // trailing days to fill 6 rows (42 cells)
  const needed = 42 - cells.length
  for (let d = 1; d <= needed; d++) {
    const date = new Date(y, m0 + 1, d)
    cells.push({
      key: `n-${d}`,
      inCurrentMonth: false,
      day: d,
      dateStr: toYmd(date.getFullYear(), date.getMonth(), date.getDate())
    })
  }
  return cells
})

function isSelected(dateStr: string) {
  return selectedDate.value === dateStr
}
function onPickDate(dateStr: string) {
  selectedDate.value = dateStr
}
function hasSchedules(dateStr: string) {
  return monthSchedules.value.some((s) => s.date === dateStr)
}
function topTwoTitles(dateStr: string) {
  return monthSchedules.value.filter((s) => s.date === dateStr).slice(0, 2)
}

function prevMonth() {
  let m0 = currentMonthIndex.value - 1
  let y = currentYear.value
  if (m0 < 0) {
    m0 = 11
    y -= 1
  }
  currentMonthIndex.value = m0
  currentYear.value = y
  loadMonth()
}
function nextMonth() {
  let m0 = currentMonthIndex.value + 1
  let y = currentYear.value
  if (m0 > 11) {
    m0 = 0
    y += 1
  }
  currentMonthIndex.value = m0
  currentYear.value = y
  loadMonth()
}

function repeatLabel(r?: RepeatType) {
  switch (r) {
    case "daily":
      return "每日"
    case "weekly":
      return "每周"
    case "monthly":
      return "每月"
    default:
      return "不重复"
  }
}

function openAddForSelected() {
  isEditing.value = false
  editingId.value = null
  errorMsg.value = ""
  form.value = {
    title: "",
    date:
      selectedDate.value ||
      toYmd(today.getFullYear(), today.getMonth(), today.getDate()),
    time: "09:00",
    repeat: "none"
  }
  dialogVisible.value = true
}

function onEdit(it: ScheduleItem) {
  isEditing.value = true
  editingId.value = it.id
  errorMsg.value = ""
  form.value = {
    title: it.title,
    date: it.date,
    time: it.time,
    repeat: it.repeat || "none"
  }
  dialogVisible.value = true
}

async function onDelete(it: ScheduleItem) {
  try {
    await sendRuntimeMessage({ type: "deleteSchedule", id: it.id })
    await loadMonth()
  } catch (e) {
    alert("删除日程失败，请重试")
  }
}

function closeDialog() {
  dialogVisible.value = false
}

function validate() {
  if (!form.value.title || !form.value.date || !form.value.time) {
    errorMsg.value = "请填写所有必填字段"
    return false
  }
  errorMsg.value = ""
  return true
}

async function onSave() {
  if (!validate()) return
  try {
    if (isEditing.value && editingId.value) {
      await sendRuntimeMessage({
        type: "updateSchedule",
        id: editingId.value,
        payload: { ...form.value }
      })
    } else {
      await sendRuntimeMessage({
        type: "addSchedule",
        payload: { ...form.value }
      })
    }
    dialogVisible.value = false
    await loadMonth()
  } catch (e) {
    alert("日程保存失败，请重试")
  }
}

async function sendRuntimeMessage(message: any): Promise<any> {
  return new Promise((resolve, reject) => {
    try {
      chrome.runtime.sendMessage(message, (resp) => {
        const lastErr = chrome.runtime.lastError
        if (lastErr) {
          reject(lastErr)
          return
        }
        if (resp && resp.ok) resolve(resp.data)
        else reject(new Error(resp?.error || "unknown"))
      })
    } catch (e) {
      reject(e as any)
    }
  })
}

async function loadMonth() {
  try {
    const data: ScheduleItem[] = await sendRuntimeMessage({
      type: "listSchedulesByMonth",
      year: currentYear.value,
      month: currentMonthIndex.value
    })
    monthSchedules.value = Array.isArray(data) ? data : []
  } catch (_e) {
    alert("日程查询失败，请重试")
  }
}

function onHelp() {
  alert(
    "添加日程提示：点击日历上的日期，然后点击“添加日程”按钮来设置新日程。\n查询日程提示：点击“查询”按钮来查看当月的所有日程。\n编辑日程提示：在日程列表中点击“编辑”来修改日程详情。\n删除日程提示：在日程列表中点击“删除”来移除日程。"
  )
}
function onFeedback() {
  alert("感谢您的反馈！请在商店评论或通过项目仓库提交。")
}

onMounted(() => {
  // init selected date to today
  selectedDate.value = toYmd(
    today.getFullYear(),
    today.getMonth(),
    today.getDate()
  )
  loadMonth()
})

watch(selectedDate, (val) => {
  try {
    chrome.action.setTitle({ title: val ? "添加新日程" : "查看日程" })
  } catch (_e) {}
})
</script>
